package top.went.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import top.went.aop.SystemLog;
import top.went.exception.InputException;
import top.went.exception.ServiceException;
import top.went.pojo.RoleEntity;
import top.went.pojo.UserEntity;
import top.went.service.GrantService;
import top.went.service.UserService;
import top.went.utils.Md5;
import top.went.utils.RegularUtils;
import top.went.vo.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Controller
//@SessionAttributes({"user", "funIds"})
public class GrantController {

    @Autowired
    private GrantService grantService;
    @Autowired
    private UserService userService;

    @GetMapping("/to_role_list")
    public String toRoleList() {
        return "admin/role_list";
    }

    @GetMapping("/to_role_add_modal")
    public String toRoleAddModal() {
        return "admin/role_add_modal";
    }

    @GetMapping("/to_role_fc_tree_modal")
    public String toRoleFcTreeModal() {
        return "admin/role_fc_tree_modal";
    }

    @GetMapping("/to_role_user_tree_modal")
    public String toRoleUserTreeModal() {
        return "admin/role_user_tree_modal";
    }

    /**
     * 分页显示所有角色
     *
     * @param pageSize
     * @param pageNumber
     * @return
     * @throws ServiceException
     */
    @GetMapping("/query_roles")
    @ResponseBody
    public PageEntity<RoleEntity> queryRoles(Integer pageSize, Integer pageNumber)
            throws ServiceException {
        return grantService.queryAllRoles(pageNumber, pageSize);
    }

    /**
     * 添加/修改角色
     *
     * @param roleEntity
     * @return
     * @throws ServiceException
     */
    @PostMapping("/role_add")
    @ResponseBody
    @SystemLog(module = "系统中心", methods = "修改角色")
    public Code addRole(RoleEntity roleEntity) throws ServiceException {
        if (roleEntity.getRoleId() == null) {
            return Code.success("添加角色成功", grantService.addRole(roleEntity.getRoleName()));
        } else {
            return Code.success("修改角色成功", grantService.modifyRole(roleEntity.getRoleId(), roleEntity.getRoleName()));
        }
    }

    /**
     * 加载角色
     *
     * @param roleId
     * @return
     * @throws ServiceException
     */
    @GetMapping("/role_load")
    @ResponseBody
    public Code roleLoad(Long roleId) throws ServiceException {
        return Code.success("加载角色成功", grantService.queryRole(roleId));
    }

    /**
     * 删除角色
     *
     * @param roleId
     * @return
     * @throws ServiceException
     */
    @GetMapping("/role_delete")
    @ResponseBody
    @SystemLog(module = "系统中心", methods = "删除角色")
    public Code roleDelete(Long roleId) throws ServiceException {
        return Code.success("删除角色成功", grantService.deleteRole(roleId));
    }

    /**
     * 查找出指定角色的所有功能列表
     *
     * @param roleId
     * @return
     * @throws ServiceException
     */
    @GetMapping("/get_function_nodes")
    @ResponseBody
    public List<FunctionNode> getFunctionNodes(Long roleId) throws ServiceException {
        return grantService.getFunctionNodes(roleId);
    }

    /**
     * 查找出指定角色的所有用户列表
     *
     * @param roleId
     * @return
     * @throws ServiceException
     */
    @GetMapping("/get_user_nodes")
    @ResponseBody
    public List<DeptVo> getDeptNodes(Long roleId) throws ServiceException {
        return grantService.getUserNodes(roleId);
    }

    /**
     * 查找出指定用户的所有角色列表
     *
     * @param userId
     * @return
     * @throws ServiceException
     */
    @GetMapping("/get_role_nodes")
    @ResponseBody
    public UserRoleNode getRolesNodes(Long userId) throws ServiceException {
        return grantService.getRoleNodes(userId);
    }

    /**
     * 给角色授权
     *
     * @param ids
     * @return
     * @throws ServiceException
     */
    @PostMapping("/grant_fc_to_role")
    @ResponseBody
    @SystemLog(module = "系统中心", methods = "给角色授权")
    public Code grantToRole(RoleIdAndFcIds ids, HttpServletRequest request) throws ServiceException {
        System.out.println("角色：" + ids.getRoleId());
        System.out.println("功能：" + ids.getFcIds());
        if (!grantService.grantFcToRole(ids))
            return Code.fail("给角色授权失败");
        UserEntity user = (UserEntity) request.getSession().getAttribute("user");
        request.getSession().setAttribute("funIds", grantService.queryFunctionIdsByUserId(user.getUserId()));
        return Code.success("角色授权成功");
    }

    /**
     * 给角色分配用户
     *
     * @param ids
     * @return
     * @throws ServiceException
     */
    @PostMapping("/grant_user_to_role")
    @ResponseBody
    @SystemLog(module = "系统中心", methods = "给角色分配用户")
    public Code grantUserToRole(RoleIdAndUserIds ids, HttpServletRequest request) throws ServiceException {
        System.out.println("角色：" + ids.getRoleId());
        System.out.println("用户:" + ids.getUserIds());
        UserEntity user = (UserEntity) request.getSession().getAttribute("user");
        request.getSession().setAttribute("funIds", grantService.queryFunctionIdsByUserId(user.getUserId()));
        return Code.success("给角色分配用户成功", grantService.grantUserToRole(ids));
    }

    /**
     * 给用户分配角色
     *
     * @param userId
     * @param ids
     * @return
     * @throws ServiceException
     * @throws NumberFormatException
     */
    @PostMapping("/grant_role_to_user")
    @ResponseBody
    @SystemLog(module = "系统中心", methods = "给用户分配角色")
    public Code grantRoleToUser(Long userId, String ids, HttpServletRequest request) throws ServiceException, NumberFormatException {
        ids = ids.substring(1, ids.length() - 1);
        System.out.println("String数据：" + ids);
        String[] a = ids.split(",");
        int[] idss = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i].substring(1, a[i].length() - 1);
            System.out.println("a[" + i + "]=" + a[i]);
            idss[i] = Integer.parseInt(a[i]);
        }
        System.out.println("int数组" + Arrays.toString(idss));

        UserEntity user = (UserEntity) request.getSession().getAttribute("user");
        request.getSession().setAttribute("funIds", grantService.queryFunctionIdsByUserId(user.getUserId()));

        return Code.success("给用户分配角色成功", grantService.grantRoleToUser(userId, idss));
    }

    /**
     * 角色名称模糊查询
     *
     * @param roleName
     * @param pageSize
     * @param pageNumber
     * @return
     * @throws ServiceException
     */
    @GetMapping("/role_find_like_name")
    @ResponseBody
    public PageEntity<RoleEntity> findRoleByRoleNameLike(String roleName, Integer pageSize,
                                                         Integer pageNumber) throws ServiceException {
        return grantService.queryRolesByRoleNameLike(roleName, pageNumber, pageSize);
    }
//    @GetMapping("/delete_fc_from_rolefc")
//    @ResponseBody
//    public Code deleteFcFromRoleFc(Long roleId) throws ServiceException {
//        return Code.success(grantService.deleteFcFromRoleFc(roleId));
//    }

    /**
     * 用户登录，并检验权限
     *
     * @param userName
     * @param userPassword
     * @param request
     * @return
     * @throws ServiceException
     */
    @PostMapping("/login_to_index")
    @ResponseBody
    @SystemLog(module = "系统功能", methods = "用户登录")
    public Code login(String userName, String userPassword, HttpServletRequest request) throws ServiceException, InputException {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(userName);
        userEntity.setUserPassword(userPassword);
        UserEntity userEntity1 = userService.findUserByName(userEntity);
        System.out.println(userEntity1);
        if (userEntity1 == null) {
            System.out.println("用户名错误");
            return Code.success("用户名错误");
        }
        if (!RegularUtils.matchAccountPassword(userPassword)) {
            System.out.println("密码格式错误");
            return Code.success("密码格式错误");
        }
        if (!userEntity1.getUserPassword().equals(Md5.encode(userPassword))) {
            Code.fail("密码错误");
            return Code.success("密码错误");
        }
        if (grantService.login(userEntity1)) {
            System.out.println("功能：" + grantService.queryFunctionIdsByUserId(userEntity1.getUserId()));
            request.getSession().setAttribute("user", userEntity1);
            request.getSession().setAttribute("funIds", grantService.queryFunctionIdsByUserId(userEntity1.getUserId()));
            return Code.success("登录成功");
        } else {
            return Code.success("对不起，登陆失败，没有登录权限！");
        }
    }
}
